import React, { PureComponent, Fragment } from 'react';
import { Form, Input, Select, TreeSelect, Button, InputNumber, Icon, notification, Tooltip } from 'antd';
import { connect } from 'dva';
import { worker } from "../../utils/worker"
/***
 * 
 * station=>x;elevation=>y1;ground_elevation=>y2
 */
class ConfigSpans extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            showForm: true,
            bridge: null,
            treeData: [],
            midStation: 0,
            minPk: 0,
            maxPk: 0,
            svalue: '', fetching: false, data: [], roadvalue: [],
            bridgeList: [],
            validateRes: null,
            abutmentTypeList: [],
            distanceMin: 0,
            distanceMax: 100,
            componentPosition: [],
            formular: "",
            expansionJoints: [],
            configWay: 1
        }
        this.onConfirm = this.onConfirm.bind(this)
        this.handleSelect = this.handleSelect.bind(this)
        this.handleSelect2 = this.handleSelect2.bind(this)
        this.handleChange = this.handleChange.bind(this)
        this.handleSearch = this.handleSearch.bind(this)
        this.reset = this.reset.bind(this)
        this.importFormular = this.importFormular.bind(this)
        this.selectBridge = this.selectBridge.bind(this)
        this.validate = this.validate.bind(this)
        this.impressionChange = this.impressionChange.bind(this)
        this.resetForm = this.resetForm.bind(this)
    }
    handleChange(val) {
        this.setState({ roadvalue: val });
    }
    async handleSearch(value) {
        if (value) {
            this.setState({
                fetching: true
            })
            let res = await this.props.queryProjectRefRoads({ projectId: this.props.project.id, name: value })
            this.setState({ data: res, fetching: false });
        } else {
            this.setState({ data: [], fetching: false });
        }
    }
    reset() {
        let { form } = this.props;
        let values = form.getFieldsValue()
        for (const key in values) {
            if (values.hasOwnProperty(key)) {
                if (!(key.toLowerCase().includes('station'))) {
                    values[key] = null
                }
            }
        }
        form.setFieldsValue(values)
    }
    handleSelect(value) {
        const obj = this.state.data.find(item => item.id == value)
        this.props.form.setFieldsValue({
            refLineCode: obj.code
        })
    }
    handleSelect2(value) {
        this.setState({
            configWay: value
        })
    }
    componentWillUnmount() {
        if (this.st) {
            clearTimeout(this.st)
        }
    }
    setFormular(lar) {
        const { form } = this.props;
        form.setFieldsValue({
            expression: lar
        })
        let res = this.validate(lar)
        this.setState({
            validateRes: res
        })
    }
    async componentDidMount() {
        let { bridgeId, project, dictlist,onLoaded,getExpansionJoint,bridgeMainAndChild,form } = this.props
        if (onLoaded) {
            onLoaded(this);
        }
        this.setState({
            abutmentTypeList: dictlist.filter(item => item.dictType == 'abutment_type'),
            componentPosition: dictlist.filter(item => item.dictType == 'expansion_joint')
        })
        if (getExpansionJoint) {
            let res = await getExpansionJoint({ projectId: project.id })
            if (res && res.length) {
                this.setState({
                    expansionJoints: res
                })
            }
        }
        if (bridgeMainAndChild) {
            let res = await bridgeMainAndChild({ projectId: project.id })
            this.setState({
                treeData: res && res.length ? await worker.loopTreeNode4(JSON.parse(JSON.stringify(res).replace(/bridges/g, 'children')), true) : []
            })
        }
        form.setFieldsValue({
            bridgeId
        })
    }
    onConfirm(params = {}) {
        let { bridge, midStation, minPk, maxPk } = this.state;
        let { configBridgeSpans, form } = this.props
        let expression = form.getFieldValue("expression")
        let res = this.validate(expression)
        this.setState({
            validateRes: res
        })
        return new Promise((resolve, reject) => {
            form.validateFields((error, values) => {
                if (!error) {
                    if (values.expression && !(/^\(/.test(values.expression))) {
                        values.expression = "(" + values.expression
                    }
                    if (values.expression && !(/\)$/.test(values.expression))) {
                        values.expression = values.expression + ")"
                    }
                    if (eval(values.expression)) {
                        const distances = eval(values.expression)
                        const st = midStation - distances / 2
                        const end = midStation + distances / 2
                        if (st - minPk < 0 || end - maxPk > 0) {
                            notification.warn({ message: "布跨不在线路里程范围之内!" })
                            if (params.onError) {
                                params.onError('error');
                            }
                            reject()
                            return;
                        }

                    }
                    this.reset()
                    configBridgeSpans(values, async (res) => {
                        if (res && res.length) {
                            const len=res.length;
                            for (let i = 0; i < len; i++) {
                                let obj = res[i];
                                if (obj.data.spans && obj.data.spans.length) {
                                    const len2=obj.data.spans.length
                                    for (let i = 0; i <len2; i++) {
                                        let item = obj.data.spans[i];
                                        item.title = item.name + ' : ' + item.code;
                                        item.key = 'botStructureDirec' + item.id;
                                        item.bridgeId = obj.bridgeId
                                        item.eventType = 'botStructureDirec'
                                        item.eventKey = 'botStructureDirec'
                                        item.checkable = true
                                        item.selectable = true
                                    }
                                    this.props.treeContext.updateTreeNode('botStructure' + obj.bridgeId, obj.data.spans)
                                }
                                if (obj.data.selectionLists && obj.data.selectionLists.length) {
                                    const len3=obj.data.selectionLists.length
                                    for (let i = 0; i < len3; i++) {
                                        let item = obj.data.selectionLists[i];
                                        item.title = item.listName + '(' + item.express + ')';
                                        item.key = 'topStructureDirec' + item.id;
                                        item.bridgeId = obj.bridgeId
                                        item.eventType = 'topStructureDirec'
                                        item.eventKey = 'topStructureDirec'
                                        item.checkable = true
                                        item.selectable = true
                                    }
                                    this.props.treeContext.updateTreeNode('topStructure' + obj.bridgeId, obj.data.selectionLists)
                                }
                            }
                        }

                        if (params.onSuccess) {
                            params.onSuccess(project);

                        }
                        resolve(`桥梁${bridge.name}布跨成功!`)
                    }, (error) => {

                        if (params.onError) {
                            params.onError('error');
                        }
                        reject()
                    });
                } else {

                    if (params.onError) {
                        params.onError('error');
                    }
                    reject()
                }
            });
        })

    }
    importFormular() {
        let { modalContext, form } = this.props;
        let expression = form.getFieldValue("expression")
        let res = this.validate(expression)
        this.setState({
            validateRes: res
        })
        if (res.validateStatus == "success") {
            modalContext.updateModal({
                visible: true,
                title: "编辑公式",
                event: { code: 'formular' },
                extra: {
                    expression
                }
            });
        } else {
            modalContext.updateModal({
                visible: true,
                title: "编辑公式",
                event: { code: 'formular' },
                extra: {

                }
            });
        }


    }
    async selectBridge(e, b) {
        const obj = b.props;
        if (obj && obj.width) {
            this.setState({
                bridge: obj,
                distanceMax: obj.width
            })
        }
        let res = await this.props.queryRoadLimit({ id: obj.roadlineId })
        if (res) {
            this.setState({
                midStation: obj.midStation,
                maxPk: res.maxPk,
                minPk: res.minPk
            })
        }
    }
    validate(value) {
        try {
            if (eval(value)) {
                if (new RegExp(/^([0-9]|\*|\+|\(|\))+$/).test(value) && typeof (eval(value)) == 'number') {

                    let arr = value.split(")+(")
                    let reg = true;

                    if (arr && arr.length) {
                        if (arr.length == 1) {
                            if (arr[0].includes("(") && arr[0].includes(")") && arr[0].split('(').length == 2 && arr[0].split(')').length == 2) {
                                return {
                                    validateStatus: 'success',
                                    errorMsg: null,
                                };
                            }
                        }
                        const len = arr.length;
                        for (let i = 0; i < len; i++) {
                            const item = arr[i];
                            if ((item.includes("(") && !item.includes(")"))||(item.includes(")") && !item.includes("("))||!new RegExp(/\(|\)/).test(item)) {

                            } else {
                                reg = false
                            }
                        }
                        if (reg) {
                            return {
                                validateStatus: 'success',
                                errorMsg: null,
                            };
                        }
                    }
                }

            }

        } catch (error) {

        }
        return {
            validateStatus: 'error',
            errorMsg: "公式设置不正确!",
        };

    }
    impressionChange(e) {
        this.setState({
            validateRes: this.validate(e.target.value)
        })
    }
    async resetForm() {
        await this.setState({
            showForm: false
        })
        this.setState({
            showForm: true
        })
    }
    render() {
        const {
            form = {},
            mode = 'add',
        } = this.props;
        let { treeData, formular, componentPosition, distanceMax, distanceMin, expansionJoints, validateRes, showForm } = this.state
        const { getFieldDecorator } = form;
        console.log(formular)
        return (
            <Form style={{ marginTop: "30px" }}
                labelAlign="right"

                labelCol={{ span: 10 }}
                wrapperCol={{ span: 14 }}
            >

                <Form.Item className="half" label='桥梁'>
                    {getFieldDecorator('bridgeId', {
                        rules: [
                            { required: true, message: '桥梁' }
                        ],
                        initialValue: undefined
                    })(
                        <TreeSelect
                            showSearch
                            treeNodeFilterProp="name"
                            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                            placeholder="请选择桥梁"
                            treeData={treeData}
                            allowClear
                            onSelect={this.selectBridge}
                            treeDefaultExpandAll


                        ></TreeSelect>
                    )}
                </Form.Item>
                {showForm ? <div className="half">
                    <div style={{ width: "100%", position: "relative" }}><Form.Item validateStatus={validateRes ? validateRes.validateStatus : null}
                        help={validateRes ? validateRes.errorMsg : null} label={<span>
                            跨径布置&nbsp;
              <Tooltip title="括号内部为一联，括号外“+”表示分隔符">
                                <Icon type="question-circle-o" />
                            </Tooltip>
                        </span>}>

                        {getFieldDecorator('expression', {
                            rules: [
                                { required: true, message: '跨径布置' },
                            ],
                            initialValue: formular ? formular : undefined

                        })(
                            <Input onChange={this.impressionChange} placeholder="请输入跨径布置" />

                        )}

                    </Form.Item><Button style={{position:"absolute",right:"-70px",top:"3px"}} onClick={this.importFormular}>设置</Button></div>
                </div> : undefined}
                <Form.Item className="half" label={<span>
                    伸缩缝位置&nbsp;
              <Tooltip title="通用设置，可在附属构件-伸缩缝中对每个孔的伸缩缝进行修改">
                        <Icon type="question-circle-o" />
                    </Tooltip>
                </span>}>
                    {getFieldDecorator('station1', {
                        rules: [
                            { required: false, message: '伸缩缝位置' }
                        ],
                        initialValue: 17
                    })(
                        <Select disabled>
                            {
                                componentPosition.map(item => {
                                    return (
                                        <Select.Option value={item.id} key={item.id}>{item.dictLabel}</Select.Option>
                                    )
                                })
                            }

                        </Select>
                    )}
                </Form.Item>


                <Form.Item className="half" label='伸缩缝型号'>
                    {getFieldDecorator('pierExpansion', {
                        rules: [
                            { required: false, message: '伸缩缝型号' }
                        ],
                        initialValue: undefined
                    })(
                        <Select placeholder="请选择伸缩缝型号" showSearch filterOption={(input, option) =>
                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }>
                            {
                                expansionJoints.map(item => {
                                    return (
                                        <Select.Option value={item.id} key={item.id}>{item.definitionName}</Select.Option>
                                    )
                                })
                            }

                        </Select>
                    )}
                </Form.Item>

                <Form.Item className="half" label={<span>
                    伸缩缝位置&nbsp;
              <Tooltip title="通用设置，可在附属构件-伸缩缝中对每个孔的伸缩缝进行修改">
                        <Icon type="question-circle-o" />
                    </Tooltip>
                </span>}>
                    {getFieldDecorator('station2', {
                        rules: [
                            { required: false, message: '伸缩缝位置' }
                        ],
                        initialValue: 18
                    })(
                        <Select disabled>
                            {
                                componentPosition.map(item => {
                                    return (
                                        <Select.Option value={item.id} key={item.id}>{item.dictLabel}</Select.Option>
                                    )
                                })
                            }

                        </Select>
                    )}
                </Form.Item>

                <Form.Item className="half" label='伸缩缝型号'>
                    {getFieldDecorator('abutmentExpansion', {
                        rules: [
                            { required: false, message: '伸缩缝型号' }
                        ]
                    })(
                        <Select placeholder="请选择伸缩缝型号" showSearch filterOption={(input, option) =>
                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        } >
                            {
                                expansionJoints.map(item => {
                                    return (
                                        <Select.Option value={item.id} key={item.id}>{item.definitionName}</Select.Option>
                                    )
                                })
                            }

                        </Select>
                    )}
                </Form.Item>

                <Form.Item className="half" label='斜交角(度)'>
                    {getFieldDecorator('angle', {
                        rules: [
                            { required: true, message: '斜交角' }
                        ],
                        initialValue: 90
                    })(
                        <InputNumber type="number" min={0} max={360} placeholder="请输入斜交角"></InputNumber>
                    )}
                </Form.Item>

                <Form.Item className="half" label={<span>
                    桥墩横向距离(m)&nbsp;
              <Tooltip title={`不得超过最大值:${distanceMax}`}>
                        <Icon type="question-circle-o" />
                    </Tooltip>
                </span>}>
                    {getFieldDecorator('distance', {
                        rules: [
                            { required: true, message: '桥墩横向距离' }
                        ]
                    })(
                        <InputNumber type="number" min={distanceMin} max={distanceMax} placeholder="请输入桥墩横向距离"></InputNumber>
                    )}
                </Form.Item>


            </Form>
        );
    }
}

export default connect(
    ({
        formular: { formular }
    }) => {
        return { formular };
    },
    dispatch => ({
        configBridgeSpans: (values, onSuccess, onError) => dispatch({
            type: 'refSpans/configSpans',
            payload: {
                values, onSuccess, onError
            }
        }),
        bridgeMainAndChild: (values) => dispatch({
            type: 'bridge/bridgeMainAndChild',
            payload: values
        }),
        queryRoadLimit: (values) => dispatch({
            type: 'bridge/queryRoadLimit',
            payload: values
        }),
        getExpansionJoint: (values) => dispatch({
            type: 'structure/getExpansionJoint',
            payload: values
        })
    })
)(Form.create('spansConfig', {

})(ConfigSpans));